package cn.kgc.service.impl;

import cn.kgc.base.dto.LockStockDTO;
import cn.kgc.commons.exception.HttpException;
import cn.kgc.entity.WmsWareInfo;
import cn.kgc.mapper.WmsWareInfoMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.kgc.mapper.WmsWareSkuMapper;
import cn.kgc.entity.WmsWareSku;
import cn.kgc.service.WmsWareSkuService;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 商品库存(WmsWareSku)表服务实现类
 *
 * @author 石浩杰
 * @since 2022-12-07 10:41:17
 */
@Service("wmsWareSkuService")
public class WmsWareSkuServiceImpl extends ServiceImpl<WmsWareSkuMapper, WmsWareSku> implements WmsWareSkuService {

    @Resource
    private WmsWareInfoMapper wmsWareInfoMapper;

    @Resource
    private WmsWareSkuMapper wmsWareSkuMapper;
    @Transactional
    public boolean lockStock(List<LockStockDTO> lockStockDTOList) {
        //遍历需要锁定的商品信息
        for (LockStockDTO lockStockDTO : lockStockDTOList) {
            String areaCode=lockStockDTO.getAreaCode();
            LambdaQueryWrapper<WmsWareInfo> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            WmsWareInfo wmsWareInfo=wmsWareInfoMapper.selectOne(lambdaQueryWrapper.eq(WmsWareInfo::getAreacode,areaCode));
            long wareId=wmsWareInfo.getId();
            //判断库存是否充足，如果库存不充足，锁定商品失败
            LambdaQueryWrapper<WmsWareSku> lambdaQueryWrapper1=new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(WmsWareSku::getSkuId,lockStockDTO.getSkuId());
            lambdaQueryWrapper1.eq(WmsWareSku::getWareId,wareId);
            WmsWareSku wmsWareSku=wmsWareSkuMapper.selectOne(lambdaQueryWrapper1);
            int nowStock=wmsWareSku.getStock()- wmsWareSku.getStockLocked();
            //库存不足
            if(nowStock<lockStockDTO.getLockStock()){
                throw new HttpException(40008, HttpStatus.INTERNAL_SERVER_ERROR.value());
            }else {
                //库存充足 原有锁定的库存+现在锁定的库存
                wmsWareSku.setStockLocked(wmsWareSku.getStockLocked()+lockStockDTO.getLockStock());
                wmsWareSkuMapper.updateById(wmsWareSku);
            }
        }
        return true;
    }
}
